use Irssi;
use Time::HiRes qw(gettimeofday);

# modified by Marco d'Itri <md@linux.it> for OPN

use vars qw($VERSION %IRSSI);
$VERSION = '10';
%IRSSI = (
	authors		=> 'fahren, David Leadbeater',
	contact		=> 'fahren@bochnia.pl',
	name		=> 'Server Ping',
	description => '/SPING server - checks latency between you and the server',
	license		=> 'GNU GPLv2 or later',
	changed		=> 'Thu Aug 15 03:38:07 CEST 2002',
);

Irssi::command_bind('sping' => 'cmd_sping');
Irssi::signal_add('event pong' => 'event_pong');
Irssi::signal_add('event 402' => 'event_nosuchserver');

my %askping;

sub cmd_sping {
	my ($target, $server, $winit) = @_;

	$target = $server->{real_address} if not $target;

	$target = complete_server_name($target);

	$askping{$target} = gettimeofday();
	# XXX this needs to be customized for your IRC daemon
#	$server->send_raw("PING $server->{real_address} $target"); # ?
	$server->send_raw("PING $target $target"); # dancer
}

sub event_pong {
	my ($server, $args) = @_;

	my ($sender, $junk) = $args =~ /^(\S+)\s:?(\S+)$/;
	if ($sender) {
		return unless exists $askping{$sender};
		Irssi::print("Latency to $sender: " .
			sprintf('%0.3f', gettimeofday() - $askping{$sender}) . 's');
		delete $askping{$sender};
	} else {
		Irssi::print("Cannot parse PONG reply '$args'");
	}

	Irssi::signal_stop();
}

sub event_nosuchserver {
	my ($server, $args) = @_;

	my ($recipient, $sender, $junk) = $args =~ /^(\S+) (\S+)\s:(.+)$/;
	return unless exists $askping{$sender};

	Irssi::print("$sender is not a valid server");
	delete $askping{$sender};
	Irssi::signal_stop();
}

sub complete_server_name {
	local $_ = $_[0] || return;

	$_ .= '.freenode.net' if not /\./;

	return $_;
}

